<?php

namespace app\controllers\wx;

use app\controllers\Controller;
use app\models\system\SetWx;
use app\models\user\User;
use app\util\Debug;
use app\util\Request;

/**
 * Class UserController
 * @package app\controllers\wx
 */
class UserController extends Controller
{
    public function actionGetOpenid()
    {
        $user_id        = $this->post('user_id');
        $redirect_url   = $this->post('redirect_url');

        // 是否获取用户信息
        $user_info      = $this->post('user_info', false);

        $openid = User::find()
            // openid 不需要过期时间
            ->where(['>', 'openid_expired', date('Y-m-d H:i:s')])
            ->andWhere(['id' => $user_id])
            ->select(['openid'])
            ->scalar();

        // 存在正确的openid
        if ($openid) {
            return $this->success([
                'openid' => $openid
            ]);
        }

        // 处理模拟openid(本地调试)
        // $debug = boolval($this->post('debug', false));
        // if ($debug) {
        //     $user = User::findOne(['id' => $user_id]);
        //     if ($user) {
        //         $user->openid = mt_rand(111111, 999999) . 'abc';
        //         $user->openid_expired = date('Y-m-d H:i:s', time() + 7200);
        //         if ($user->save()) {
        //             return $this->success([
        //                 'openid' => $user->openid
        //             ]);
        //         }
        //     }
        // }

        // 请求微信api(需要前端配合处理)
        // 主要是生成url给前端
        return $this->success([
            'url' => $this->getWxUrl($user_id, $redirect_url, $user_info)
        ]);
    }

    private function getWxUrl($user_id, $redirect_url, $user_info = false)
    {
        $wx = SetWx::getLastOne(false);

        $scope = 'snsapi_base';
        $redirect_url = urlencode($redirect_url);

        // get user info
        if ($user_info) {
            $scope = 'snsapi_userinfo';
        }

        return "https://open.weixin.qq.com/connect/oauth2/authorize" .
            "?appid={$wx->app_id}&redirect_uri={$redirect_url}&response_type=code&scope={$scope}&state={$user_id}#wechat_redirect";
    }

    public function actionGet()
    {
        $code       = $this->post('code');
        $user_id    = $this->post('user_id');

        $wx = SetWx::getLastOne(false);

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token" .
            "?appid={$wx->app_id}&secret={$wx->app_secret}&code={$code}&grant_type=authorization_code";

        /**
         * 正确时返回的JSON数据包如下：
         * {
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE"
        }
         */
        try {
            $result = Request::get($url);
            $result = json_decode($result);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }

        if ($result && $result->openid) {
            $user = User::findOne(['id' => $user_id]);
            if (!$user) {
                return $this->fail('用户错误');
            }

            $user->openid = $result->openid;
            $user->openid_expired = date('Y-m-d H:i:s', $result->expires_in + time() - 200);

            if ($user->save()) {
                /**
                 * {
                "openid": "OPENID",
                "nickname": NICKNAME,
                "sex": 1, 值为1时是男性，值为2时是女性，值为0时是未知
                "province":"PROVINCE",
                "city":"CITY",
                "country":"COUNTRY",
                "headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
                "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
                "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
                }
                 */

                // user info
                // 需要关注公众号
                try {
                    $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$result->access_token}&openid={{$result->openid}}&lang=zh_CN";
                    $info = Request::get($url);
                    $info = json_decode($info);
                    if ($info && $info->nickname && $info->headimgurl) {
                        $user->nickname = base64_encode($info->nickname);
                        $user->avatar = $info->headimgurl;
                        // 这个获取不到的
                        // $user->unionid = $info->unionid;
                        $user->sex = $info->sex;
                        $user->save();
                    }
                } catch (\Exception $e) {
                    Debug::wx('get-info', $e->getMessage());
                }

                return $this->success([
                    'openid' => $user->openid
                ]);
            }
        }

        return $this->fail('获取openid(用户信息)失败');
    }
}